package com.zx.framework.core.util;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyShell;

import java.io.File;

import org.apache.log4j.Logger;

import com.zx.framework.core.exception.FrameworkException;

/**
 * 用来执行groovy文件或类
 * 
 * @author stylewolf
 * 
 */
public class GroovyUtil
{
	private static final Logger LOG = Logger.getLogger(GroovyUtil.class);
	
	public static Object evaluateScript(String script,Binding binding)
	{
		Object result = null;
		try
		{
			GroovyShell gs = null;
			if(binding==null)
			{
				gs = new GroovyShell();			
			}else
			{
				gs = new GroovyShell(binding);			
			}
			
			result = gs.evaluate(script);
		} catch (Exception e)
		{
			LOG.error("执行groovy文件失败！",e);
			throw new FrameworkException(e);
		} 

		return result;
	}
	/**
	 * 执行groovy文件
	 * 
	 * @param fileName groovy文件绝对路径
	 * @return
	 */
	public static Object evaluate(String fileName,Binding binding)
	{
		File file = new File(fileName);

		return evaluateFile(file,binding);
	}
	/**
	 * 执行groovy文件
	 * 
	 * @param fileName groovy文件绝对路径
	 * @return
	 */
	public static Object evaluateFile(File file,Binding binding)
	{
		Object result = null;
		try
		{
			GroovyShell gs = null;
			if(binding==null)
			{
				gs = new GroovyShell();			
			}else
			{
				gs = new GroovyShell(binding);			
			}
			
			result = gs.evaluate(file);
		} catch (Exception e)
		{
			LOG.error("执行groovy文件失败！",e);
			throw new FrameworkException(e);
		} 
		return result;
	}
	/**
	 * 获得groovy中的类对象
	 * @param fileName groovy文件绝对路径
	 * @return
	 */
	public static GroovyObject getGroovyObject(String fileName,Binding binding)
	{
		GroovyClassLoader loader = new GroovyClassLoader();
		GroovyObject groovyObject = null;
		File file = new File(fileName);
		try
		{
			Class<?> groovyClass = loader.parseClass(file);
			groovyObject = (GroovyObject) groovyClass.newInstance();
		} catch (Exception e)
		{
			throw new FrameworkException(e);
		}	
		return groovyObject; 
	}
}
